WebApi 在部署到 Azure 网站时不起作用
本文关键字:网站 不起作用 Azure 部署 WebApi | 更新日期: 2023-09-27 18:35:16
我的WebApi在我的本地计算机上运行良好,但是当发布到Azure(Azure网站)时,我得到以下信息:
找不到与请求 URI 匹配的 HTTP 资源 "http://myazurewebsite.domain/Api/Zipcode/GetLatLong?zip5=23423"。
但是在本地主机上,它工作得很好。
http://localhost/Api/Zipcode/GetLatLong?zip5=20024
{"Latitude":38.89,"Longitude":-77.03}
我有一个修改过的WebApi路由:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultPublicApi",
routeTemplate: "Api/{controller}/{action}/{id}/{format}",
defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional}
);
}
}
接口控制器类:
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Project.Geography.Services;
using Project.WebPublic.Filters;
namespace Project.WebPublic.Controllers.WebApi
{
public class ZipCodeController : ApiController
{
private readonly ZipCodeService _zipCodeService;
public ZipCodeController(ZipCodeService zipCodeService)
{
_zipCodeService = zipCodeService;
}
[HttpGet]
[TransactionFilter]
public HttpResponseMessage GetLatLong(string zip5)
{
if (zip5.Length != 5)
return Request.CreateResponse(HttpStatusCode.BadRequest, "Zip Code Length Not Equal to 5");
var zip = _zipCodeService.GetByZip5(zip5);
if (zip == null)
return Request.CreateResponse(HttpStatusCode.NotFound, "Could not find Zip Code in Database");
var latlong = new
{
Latitude = zip.Latitude,
Longitude = zip.Longitude
};
return Request.CreateResponse(HttpStatusCode.OK, latlong);
}
}
}
尝试添加路由,如下所示
[HttpGet]
[TransactionFilter]
[Route("api/GetLatLong")]
public HttpResponseMessage GetLatLong(string zip5)
{
if (zip5.Length != 5)
return Request.CreateResponse(HttpStatusCode.BadRequest, "Zip Code Length Not Equal to 5");
var zip = _zipCodeService.GetByZip5(zip5);
if (zip == null)
return Request.CreateResponse(HttpStatusCode.NotFound, "Could not find Zip Code in Database");
var latlong = new
{
Latitude = zip.Latitude,
Longitude = zip.Longitude
};
return Request.CreateResponse(HttpStatusCode.OK, latlong);
}
然后您的路由配置如下所示
public static class WebApiConfig
{
/// <summary>
/// Register the http configuration for web API.
/// </summary>
/// <param name="config">The http configuration instances</param>
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}