我在web API中使用自定义oauth进行身份验证。现在我想从MVC控制器调用web api方法。 Web 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或http://localhost:55362/api/UserById?idvalue=2。它不适用于httpclient调用。
答案 0 :(得分:0)
确保您已在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} );
答案 1 :(得分:0)
如果您仍然坚持这个问题,请注意。请执行以下操作以使其正常工作。
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;
}
}
让我知道这是否有效