通过传递 oauth 令牌和参数来调用 web api c#
Call web api c# by passing oauth token along with parameter
我在网络中使用自定义 oauth API 进行身份验证。现在我想从 MVC 控制器调用 web api 方法。
网络 API 方法:
public class UserController : ApiController
{
[Authorize(Roles = "Admin")]
[HttpPost]
[ActionName("UserById")]
public IEnumerable GetUserById(string idValue)
{
long ID = idValue != "" ? Convert.ToInt64(idValue) : -1;
using (var db = new DataModelContext())
{
IEnumerable query = (from b in db.User.Include(u => u.EmailAddresses).ToList()
where b.Id == ID
select new { b.Id, UserName = b.UserName, b.EmailAddresses }).ToList();
return query;
}
}
}
MVC 控制器:
public class PagesController : Controller
{
public ActionResult GetUserById(long id)
{
string baseUrl = Common.GetAPIUrl();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Common.GetoAuth().access_token);
var values = new JObject();
values.Add("idValue",id.ToString());
HttpContent content = new StringContent(values.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsJsonAsync(baseUrl + "/api/User/UserById", content).Result;
string resultJSON = response.Content.ReadAsStringAsync().Result;
return View("UserDetail",resultJson);
}
}
它为什么不起作用,我无法纠正它为什么不起作用的问题。当我从邮递员直接呼叫 API URL 时,它工作正常。喜欢 http://localhost:55362/api/UserById/2 or http://localhost:55362/api/UserById?idvalue=2。它不适用于 httpclient 调用。
确保您已在 webapiconfig.cs 文件中启用 CORS。
此外,请验证您的路由映射
public static void Register(HttpConfiguration config)
{
var mvcSiteURL = "Define your MVC site URL here"; //Example: http://localhost:5906
var cors = new EnableCorsAttribute(mvcSiteURL, "*", "*");
config.EnableCors(cors);
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional} );
万一你仍然坚持这个问题。请执行以下操作以使其正常工作。
WebApiConfig: Action Api 应该在控制器 Route
之上
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{Action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
关于Api方法:将"FromBody"属性添加到参数中。
[Authorize(Roles = "Admin")]
[HttpPost]
[ActionName("UserById")]
public IEnumerable GetUserById([FromBody]string idValue)
{
long ID = idValue != "" ? Convert.ToInt64(idValue) : -1;
using (var db = new DataModelContext())
{
IEnumerable query = (from b in db.User.Include(u => u.EmailAddresses).ToList()
where b.Id == ID
select new { b.Id, UserName = b.UserName, b.EmailAddresses }).ToList();
return query;
}
}
让我知道这是否有效
我在网络中使用自定义 oauth API 进行身份验证。现在我想从 MVC 控制器调用 web api 方法。 网络 API 方法:
public class UserController : ApiController
{
[Authorize(Roles = "Admin")]
[HttpPost]
[ActionName("UserById")]
public IEnumerable GetUserById(string idValue)
{
long ID = idValue != "" ? Convert.ToInt64(idValue) : -1;
using (var db = new DataModelContext())
{
IEnumerable query = (from b in db.User.Include(u => u.EmailAddresses).ToList()
where b.Id == ID
select new { b.Id, UserName = b.UserName, b.EmailAddresses }).ToList();
return query;
}
}
}
MVC 控制器:
public class PagesController : Controller
{
public ActionResult GetUserById(long id)
{
string baseUrl = Common.GetAPIUrl();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Common.GetoAuth().access_token);
var values = new JObject();
values.Add("idValue",id.ToString());
HttpContent content = new StringContent(values.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsJsonAsync(baseUrl + "/api/User/UserById", content).Result;
string resultJSON = response.Content.ReadAsStringAsync().Result;
return View("UserDetail",resultJson);
}
}
它为什么不起作用,我无法纠正它为什么不起作用的问题。当我从邮递员直接呼叫 API URL 时,它工作正常。喜欢 http://localhost:55362/api/UserById/2 or http://localhost:55362/api/UserById?idvalue=2。它不适用于 httpclient 调用。
确保您已在 webapiconfig.cs 文件中启用 CORS。
此外,请验证您的路由映射
public static void Register(HttpConfiguration config)
{
var mvcSiteURL = "Define your MVC site URL here"; //Example: http://localhost:5906
var cors = new EnableCorsAttribute(mvcSiteURL, "*", "*");
config.EnableCors(cors);
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional} );
万一你仍然坚持这个问题。请执行以下操作以使其正常工作。
WebApiConfig: Action Api 应该在控制器 Route
之上 config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{Action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
关于Api方法:将"FromBody"属性添加到参数中。
[Authorize(Roles = "Admin")]
[HttpPost]
[ActionName("UserById")]
public IEnumerable GetUserById([FromBody]string idValue)
{
long ID = idValue != "" ? Convert.ToInt64(idValue) : -1;
using (var db = new DataModelContext())
{
IEnumerable query = (from b in db.User.Include(u => u.EmailAddresses).ToList()
where b.Id == ID
select new { b.Id, UserName = b.UserName, b.EmailAddresses }).ToList();
return query;
}
}
让我知道这是否有效