我有一个仅用于向我们的应用程序发出API请求的项目,而我们正在使用ASP.NET MVC 4项目。我们有一些从ApiController派生的控制器,而另一些从普通Controller类派生的控制器。问题是我不希望ApiControllers的默认路由api/XXXXX/。我希望ApiController与非Api控制器使用相同的路由{controller}/{action}/{id}。我尝试添加以下路线
routes.MapHttpRoute(
name: "Api",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
这样就可以使用常规{controller}/{action}路由访问我的ApiController,但是不再可以访问“常规”控制器。如果我摆脱MapHttpRoute了相反的情况。
是否可以通过相同的url路由访问ApiControllers和“普通”控制器?
调用下面显示的方法时,Request始终为null.我有一些简单的方法从MVC4 app中的控制器返回JSON数据,控制器使用ApiController作为基类.我的目录函数的代码如下:
public HttpResponseMessage GetDirectory() {
try {
var dir = r.GetDirectory();
if (dir == null) {
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
var response = Request.CreateResponse(HttpStatusCode.OK, dir, "application/json");
response.Headers.Location = new Uri(Request.RequestUri, "directory");
return response;
} catch (Exception ex) {
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
Run Code Online (Sandbox Code Playgroud)
调用此方法时,从r.GetDirectory()正确加载'dir'.但请求为空.所以Request.CreateResponse()自然会失败,等等.我正在寻找Request为null的原因,或者为了允许返回仍为HttpResponseMessage的重写.
这被称为(在我的单元测试项目中):
var ctrl = new DirectoryController();
var httpDir = ctrl.GetDirectory();
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
我有一个普通的ASP.NET MVC项目(不是Web API).在这里,我在我的控制器中创建了一个名为"api"的新文件夹,因为我想创建一个简单的api.
然后我创建以下类:
public class OfficeProductController : ApiController
{
[HttpPost]
public JsonResult Create(OfficeProductViewModel model)
{
var obj = new OfficeProductViewModel();
return Json(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里我遇到两个问题:
如果我没记错的话,这可以在web api项目中使用.
我究竟做错了什么?我需要添加什么?
我正在尝试将带有 JWT 的令牌身份验证添加到我的 .Net Core 2.0 应用程序中。我有一个简单的控制器,它返回一个用于测试的用户列表。
[Authorize]
[Route("api/[controller]")]
public class UsersController : Controller
{
...
[HttpGet]
[Route("api/Users/GetUsers")]
public IEnumerable<ApplicationUser> GetUsers()
{
return _userManager.Users;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个用于令牌安全的 API 控制器。它有一个登录方法,它返回一个 Token 字符串结果。
[HttpPost(nameof(Login))]
public async Task<IActionResult> Login([FromBody] LoginResource resource)
{
if (resource == null)
return BadRequest("Login resource must be asssigned");
var user = await _userManager.FindByEmailAsync(resource.Email);
if (user == null || (!(await _signInManager.PasswordSignInAsync(user, resource.Password, false, false)).Succeeded))
return BadRequest("Invalid credentials");
string result = GenerateToken(user.UserName, resource.Email);
// Token is created, we can sign out …Run Code Online (Sandbox Code Playgroud) 我试图拦截所有异常,但是代码永远不会运行。我尝试将其放到GlobalFilters,也直接将其放到我的方法上。
我的属性:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleExceptionAttribute : HandleErrorAttribute
{
private ILog log = LogManager.GetLogger(typeof(HandleExceptionAttribute));
public override void OnException(ExceptionContext filterContext)
{
log.Info("inside on exception"); // this never appears
}
}
Run Code Online (Sandbox Code Playgroud)
我的课:
public class Tester
{
[HandleException]
public void Except()
{
var asd = 0;
var qwe = 1 / asd;
}
}
Run Code Online (Sandbox Code Playgroud)
除以零会给我一个异常,调试器会捕获它,我继续,但是没有任何内容写入日志文件。
记录器正常工作。其他日志出现在文件中。即使禁用调试,它也不会读取日志文件,因此这不是调试器的错误。
在IIS Express上运行它。Windows 7的。
编辑:
将东西移到控制器上。还是行不通
public class UserController : ApiController
{
private ILog log = LogManager.GetLogger(typeof(UserController));
[HandleException] …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc exception-handling asp.net-mvc-4 asp.net-apicontroller
我试图通过允许其中一个参数作为管道分隔的字符串传递来修改我的一个api控制器以允许创建多个预留.方法和类可以在这里看到:
public class ReservationsController : ApiController
{
public HttpResponseMessage PostReservation(string eRaiderUserName, string SpaceNumbers)
{
char[] delimiter = { '|' };
string[] spaces = SpaceNumbers.Split(delimiter);
bool saved = true;
foreach(string space in spaces)
{
var reservation = new Reservation { eRaiderUserName=eRaiderUserName, SpaceNumber=Convert.ToInt32(space) };
if (true)
{
reservation.Game = db.Games.FirstOrDefault(g => g.ID == AppSettings.CurrentGameID);
db.Reservations.Add(reservation);
db.SaveChanges();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, reservation);
//response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = reservation.ID }));
//return response;
}
else
{
saved = false;
//return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); …Run Code Online (Sandbox Code Playgroud) 我正试图让我的apicontroller工作.但不知怎的,我不能回来Json().
这是编译器的错误消息:
错误CS0029无法将类型'System.Web.Http.Results.JsonResult <>'隐式转换为'System.Web.Mvc.JsonResult'Opten.Polyglott.Web D:\ Development\git\Opten.Polyglott\src\Opten.Polyglott名.web \控制器\ NewsletterApiController.cs
我无法解释为什么它无法转换Json()为ActionResult偶数的Json()继承ActionResult.
这是我的控制器:
using MailChimp;
using MailChimp.Helper;
using Opten.Polyglott.Web.Models;
using Opten.Umbraco.Common.Extensions;
using System.Configuration;
using System.Web.Mvc;
using Umbraco.Core.Logging;
using Umbraco.Web.WebApi;
namespace Opten.Polyglott.Web.Controllers
{
public class NewsletterApiController : UmbracoApiController
{
public ActionResult Subscribe(Newsletter newsletter)
{
bool isSuccessful = false;
if (ModelState.IsValid)
{
isSuccessful = SubscribeEmail(newsletter.Email);
}
return Json(new { isSuccess = isSuccessful });
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
更新的完整解决方案:
我要测试的 WebApi 控制器方法:
using Microsoft.AspNet.Identity;
using System.Web.Http;
[Authorize]
public class GigsController : ApiController
{
private readonly IUnitOfWork _unitOfWork;
public GigsController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpDelete]
public IHttpActionResult Cancel(int id)
{
var userId = User.Identity.GetUserId();
var gig = _unitOfWork.Gigs.GetGigWithAttendees(id);
if (gig.IsCanceled)
return NotFound();
if (gig.ArtistId != userId)
return Unauthorized();
gig.Cancel();
_unitOfWork.Complete();
return Ok();
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试类:
[TestClass]
public class GigsControllerTests
{
private GigsController _controller;
public GigsControllerTests()
{
var identity = new GenericIdentity("user1@domain.com");
identity.AddClaim(
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "user1@domain.com"));
identity.AddClaim(
new …Run Code Online (Sandbox Code Playgroud) 我制作了一个 API,在实体框架详述之后,我发送了一个在 Json 中序列化的对象。
我的对象:
public class Package
{
public int Items { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public double? Weight { get; set; }
public string Size { get; set; }
public string PackageType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当收到它(Xamarin 应用程序)后,问题就开始了,Json 的第一个字母小写,但我想在完全相同的类中反序列化它,但不能,因为该类具有大写的属性(C# 标准)。现在我正在使用一个可怕的“助手”类,它具有小写的属性来翻译它。
知道如何处理这个问题并直接用大写首字母发送 Json 吗?
编辑
我使用ASP.NET Web API Core和Newtonsoft.Json
在 Xamarin 应用程序中,我使用System.Text.Json
我正在开发ASP.NET Core 2.0 RESTful API.我有一个场景,我需要使用HTTPGet方法在我的API控制器上调用操作,我需要提取用于调用另一个第三方API的用户名和密码值.用户名和密码与当前登录的用户标识无关,它们只是我想从我自己的API中发送到另一个API的值,但我不想只是在查询字符串中传递它们.
我可以在客户端中使用基本身份验证将用户名和密码添加到HttpRequestMessage身份验证标头中,然后在我的ASP.NET Core 2.0 API控制器操作中提取该标头吗?
我的客户端会在调用API的代码中出现类似的内容
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, relativeUrl);
var byteArray = new UTF8Encoding().GetBytes(string.Format($"username:password"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Run Code Online (Sandbox Code Playgroud)
而且,我的API控制器动作会启动这样的事情;
[HttpGet()]
public IActionResult GetUploadedFileList([FromQuery]int pageNumber, [FromQuery]int pageSize)
{
//Extract Authentication header values for username and password
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以提供如何从HTTPGet请求获取Authorization标头的示例
我意识到我可以使用HTTPPost [FromBody]轻松完成此操作,但我的用例要求此方法为HTTGet.
在此先感谢您的帮助.
编辑1 - 解决方案
由于此链接提供了一些提示,我能够让下面的代码工作.虽然这似乎很多工作,所以如果有人有更好或更清洁的解决方案,请发布你的例子.
[HttpGet()]
public IActionResult GetUploadedFiles([FromQuery]int pageNumber, [FromQuery]int pageSize)
{
string username = string.Empty;
string password = string.Empty;
if (Request.Headers.TryGetValue("Authorization", out StringValues authToken))
{
string authHeader = authToken.First(); …Run Code Online (Sandbox Code Playgroud) http-headers dotnet-httpclient asp.net-apicontroller asp.net-core-2.0
在我的解决方案中,我直接在根目录中Startup.cs文件旁边有一个名为beep.png的文件。我将其属性更改为始终复制。我激活了UseFileServer并选择浏览目录结构以确定。
但是,当我运行代码时Image.FromFile("beep.png");,我只收到找不到文件的错误。
System.IO.FileNotFoundException
Message=C:\Program Files\IIS Express\beep.png
如何才能使该文件可供访问?
当我使用 Web api 调用下载文件时,我可以轻松下载该文件。唯一的问题是,在我的错误日志中发送 HTTP 标头后,我收到“服务器无法设置状态”。抱歉,如果这可能是重复的问题,但这里的答案都没有帮助我。
<a href="/api/DownloadDocumentById?documentId=<%=doc.Id %>" download>
<i class="fa fa-download text-primary"></i>
</a>
Run Code Online (Sandbox Code Playgroud)
<HttpGet>
<ActionName("DownloadDocumentById")>
Public Function DownloadDocumentById(documentId As Integer)
Dim document = xxxxxxxx
Dim context = HttpContext.Current
context.Response.ContentType = document.Type
context.Response.OutputStream.Write(document.Content, 0, document.Size)
context.Response.AddHeader("Content-Disposition", Baselib.FormatContentDispositionHeader($"{document.Name}"))
context.Response.AddHeader("Last-Modified", DateTime.Now.ToLongDateString())
context.Response.Flush()
context.Response.End()
Return HttpStatusCode.OK // Have also tried to create a sub without returning a value
End Function
Run Code Online (Sandbox Code Playgroud)
如前所述,我可以轻松下载该文档,但 IIS 仍然记录“HTTP 标头已发送后服务器无法设置状态”错误。再次抱歉,这是一个重复的问题。希望可以有人帮帮我。
vb.net webforms download asp.net-web-api asp.net-apicontroller
c# ×6
asp.net-mvc ×4
asp.net-core ×2
json ×2
.net-core ×1
api ×1
asp.net ×1
controller ×1
download ×1
http-headers ×1
tdd ×1
unit-testing ×1
vb.net ×1
webforms ×1