C# MVC无法访问API控制器操作
我当前无法访问我的api控制器操作。我有一个MVC应用程序,它通过javascript中的ajax调用调用api 我的API方法是:C# MVC无法访问API控制器操作,c#,ajax,asp.net-mvc,api,C#,Ajax,Asp.net Mvc,Api,我当前无法访问我的api控制器操作。我有一个MVC应用程序,它通过javascript中的ajax调用调用api 我的API方法是: [HttpPost, Route("api/Communication/AddLink")] public HttpResponseMessage AddLink([FromBody]int id) { //DO STUFF return Request.CreateResponse(HttpStatusCode.OK, returnData);
[HttpPost, Route("api/Communication/AddLink")]
public HttpResponseMessage AddLink([FromBody]int id)
{
//DO STUFF
return Request.CreateResponse(HttpStatusCode.OK, returnData);
}
我的ajax调用是:
$.ajax({
cache: false,
url: serviceEndpoint + 'api/Communication/AddLink',
type: 'POST',
data: { id: commid },
headers:{
Authorization: 'Bearer ' + token
},
success: function (data) {
console.log(data);
}
});
我按如下方式检索我的令牌:
public async static Task<AuthenticationResult> GetTokenAsync(AuthenticationContext ctx, string resourceId)
{
ClientCredential credential = new ClientCredential(OfficeSettings.ClientId, OfficeSettings.ClientSecret);
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
UserIdentifier ident = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
var redirectUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
try
{
AuthenticationResult result = await ctx.AcquireTokenSilentAsync(resourceId, credential, ident);
//var result = await ctx.AcquireTokenAsync(resourceId, credential);
LastAuthority = ctx.Authority;
return result;
}
catch (AdalException e)
{
logger.Error(e, "AcquireTokenSilentAsync: " + e.Message);
ctx.TokenCache.Clear();
return null;
}
catch (Exception ex)
{
throw ex;
}
}
任何与此相关的帮助都将不胜感激,因为我对这一点没有想法。我很高兴提供进一步的代码和信息,如果需要的话
谢谢
编辑
一点额外的信息。我的Api设置为从localhost:44391开始,但是当它加载时,url是。这是否可能表明启动时出现了问题?如果是这样,我如何正确调试它?您没有发布到正确的url。您的路由定义为
api/Communication/AddLink
。但是你正在发布到api/Communication/AddLink/{id}
@Amy道歉,这是一个旧版本,url现在已经更改,我将更新now@ssimeonov我看了一下,但我不确定我是否理解你能详细解释一下吗?我不明白这与我的问题有什么关系。别担心,我也不明白这与我的问题有什么关系。
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// DI Config
var container = new UnityContainer();
/// Register Types
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
}
IDX10803: Unable to create to obtain configuration from: 'https://login.microsoftonline.com/.well-known/openid-configuration'