在常规课程中,我需要阅读以下内容HttpContext:
控制器和操作名称
动作的属性(我可以通过HttpActionContext.ActionDescriptor.GetCustomAttributes<type>() 但这里我没有HttpActionContext- 我只有HttpContext)
阅读论证(例如actionContext.ActionArguments["paramName"],但同样 - 我只有一个HttpContext)
它不是动作过滤器,也不是控制器类。但是,我可以访问HttpContext.
httpcontext routedata asp.net-web-api actioncontext asp.net-web-api2
当我们想在 ASP.NET Core 的管道中将对象序列化为 JSON 字符串时,我们需要使用HttpContext.Response.Body.WriteAsync,除非我遗漏了一些东西,因为没有Result可以轻松用于分配JsonResult对象的属性。
除非有更好的替代方案,否则使用上述方法究竟是如何实现序列化的?
注意: JSON 序列化程序的选项应与 ASP.NET Core 3.1 中使用的(默认)选项相同。
如果需要(不是在我们的例子中),它们可以通过IServiceCollection.AddJsonOptions中间件进行修改。
例子:
app.Use( next =>
{
return async context =>
{
if (<someFunkyConditionalExample>)
{
// serialize a JSON object as the response's content, returned to the end-user.
// this should use ASP.NET Core 3.1's defaults for JSON Serialization.
}
else
{
await next(context);
}
};
});
Run Code Online (Sandbox Code Playgroud) 我的基本控制器类BaseController由面向公众的控制器继承,以访问具有LINQ-to-SQL的请求之间的共享数据上下文.
HttpContext.Current.Items每个HTTP请求中以高效和安全的方式访问我的数据上下文?DataContextHelper 类internal static class DataContextHelper
{
public static MyDataContext CurrentContext
{
get
{
if (HttpContext.Current.Items["MyDataContext"] == null)
{
MyDataContext context = new MyDataContext();
HttpContext.Current.Items["MyDataContext"] = context;
}
return (MyDataContext)HttpContext.Current.Items["MyDataContext"];
}
}
}
Run Code Online (Sandbox Code Playgroud)
BaseController 类:public class BaseController : Controller
{
protected MyDataContext db
{
get {
return DataContextHelper.CurrentContext;
}
}
}
Run Code Online (Sandbox Code Playgroud)
HomeController 类:[HandleError]
public class HomeController : BaseController // inherits db member
{
public ActionResult SomeAction(string id)
{
User user = db.Users.First(u …Run Code Online (Sandbox Code Playgroud) 我今天遇到了一个奇怪的问题,对我来说毫无意义.以下是摘要:
在方法内部,我检查一个缓存的项目如下:
private async Task<RatesStatus> getRatesStatusAsync() {
//...
if (_currentHttpContext != null) {
//Here, I am checking for a Cached item
var cachedRatesStatusObj = HttpContext.Current.Cache[Constants.RATESSTATUS_CACHE_KEY_NAME];
if (cachedRatesStatusObj != null)
return (RatesStatus)cachedRatesStatusObj;
}
//...
cacheRatesStatusObject(ratesStatus);
//...
}
Run Code Online (Sandbox Code Playgroud)
这里,HttpContext.CurrentASP.NET应用程序中的预期值不是预期的.然后,在cacheRatesStatusObject方法内部,我检查是否HttpContext.Current为null,如下所示:
private void cacheRatesStatusObject(RatesStatus ratesStatus) {
//...
//Seeing if HttpContext.Current is null or not first.
//and it is null here...
if (HttpContext.Current == null)
return;
//...
}
Run Code Online (Sandbox Code Playgroud)
它在那里是空的.不知道这里发生了什么.有什么想法吗?
有没有办法使用HttpContext或View上下文来获取当前的操作名称?
我可以使用控制器名称
var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
if (routeValues != null)
{
if (routeValues.ContainsKey("controller"))
{
controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}
}
}
Run Code Online (Sandbox Code Playgroud) 我想测试我的MVC应用程序,并且想模拟HttpContext。我正在使用Moq框架,这是我模拟HttpContext所做的工作:
[SetUp]
public void Setup()
{
MyUser myUser = new MyUser();
myUser.Id = 1;
myUser.Name = "AutomatedUITestUser";
var fakeHttpSessionState =
new FakeHttpSessionState(new SessionStateItemCollection());
fakeHttpSessionState.Add("__CurrentUser__", myUser);
ControllerContext mockControllerContext = Mock.Of<ControllerContext>(ctx =>
ctx.HttpContext.User.Identity.Name == myUser.Name &&
ctx.HttpContext.User.Identity.IsAuthenticated == true &&
ctx.HttpContext.Session == fakeHttpSessionState &&
ctx.HttpContext.Request.AcceptTypes ==
new string[]{ "MyFormsAuthentication" } &&
ctx.HttpContext.Request.IsAuthenticated == true &&
ctx.HttpContext.Request.Url == new Uri("http://moqthis.com") &&
ctx.HttpContext.Response.ContentType == "application/xml");
_controller = new SomeController();
_controller.ControllerContext = mockControllerContext; //this line is not working
//when I see _controller.ControllerContext in …Run Code Online (Sandbox Code Playgroud) 我避免使用默认的ASP.NET方法来重定向错误(就像许多人一样).清洁AJAX代码和SEO是原因之一.
但是,我正在使用以下方法来执行此操作,似乎我可能会HttpContext.Current.Items在转移中丢失?
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="401" />
<remove statusCode="403" />
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="401" responseMode="ExecuteURL" path="/Account/SignIn" />
<error statusCode="403" responseMode="ExecuteURL" path="/Site/Forbidden" />
<error statusCode="404" responseMode="ExecuteURL" path="/Site/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Site/Error" />
</httpErrors>
Run Code Online (Sandbox Code Playgroud)
我认为它只是执行了一个Server.Transfer()封面,我理解保留Items.(参见:HttpContext.Current.Items的范围和http://weblog.west-wind.com/posts/2010/Jan/20/HttpContextItems-and-ServerTransferExecute)
但是我也在Items"ExecuteURL"之前捕获了一些内容,并在转移之后检索/输出它(或者它是什么),它似乎消失了.我已经看到它进入Items集合,我看到Count加注到5,然后当检索到值时,集合中只有2个项目.
到底是怎么回事?
如果你想更多地了解我正在做的事情并推荐一个替代实现,我愿意接受它.我正在使用它以一种没有竞争条件的方式将ELMAH Error Id推送到ViewModel中.(即我正在替换的常见解决方法是仅显示最近的错误.)这是我的代码:
Global.asax中
protected void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) {
ElmahSupplement.CurrentId = args.Entry.Id;
}
void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e) {
if (ElmahSupplement.IsNotFound(e.Exception)) …Run Code Online (Sandbox Code Playgroud) 嗨,我想将参数传递给asp.net核心中的自定义策略。据我所知,我只能做
[Authorize(Policy="Over21")]
My Action(){
}
Run Code Online (Sandbox Code Playgroud)
但我想做
[Authorize(Policy="Over21",Para="AnotherValue")]
My Action(){
}
Run Code Online (Sandbox Code Playgroud)
所以我决定扩展Authorize属性,然后执行此操作。
public class MyAuthorizationAttribute : AuthorizeAttribute
{
public string Permission;
public MyAuthorizationAttribute(string policy, string permission)
: base(policy)
{
Permission = permission;
}
}
Run Code Online (Sandbox Code Playgroud)
然后做这个
[MyAuthorization("MyPolicy","CanDoPermission")]
My Action(){
}
Run Code Online (Sandbox Code Playgroud)
调试时仍会调用自定义授权处理程序,因此现在我想要一种从中获取权限属性的方法AuthorizationHandlerContext context。我意识到在调试过程中向下钻取时可以找到此属性
context->Resource->Filters
Run Code Online (Sandbox Code Playgroud)
在此列表中,我找到了AuthorizeFilter类型的所有对象,并进一步深入AuthorizeData->Resultview到此列表中还包含MyAuthorization对象。我使用首次登台工具执行此操作,但我不知道如何获取适用于所调用特定操作的MyAuthorization实例?
这是我得到的最远的。
var mvcContext = context.Resource as AuthorizationFilterContext;
foreach (var filterMetadata in mvcContext.Filters)
{
if (filterMetadata.GetType().Name != "AuthorizeFilter") continue;
var claimAttribute = filterMetadata as AuthorizeFilter;
if (claimAttribute != null)
{
var data = claimAttribute.AuthorizeData;
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Asp.Net Core 2中的ActionFilter在页面上附加一些HTML和Javascript内容。
在MVC中,它与
filterContext.HttpContext.Response.Write(stringBuilder.ToString());
Run Code Online (Sandbox Code Playgroud)
但是在Core中它不起作用。
我试图用这个实现:
filterContext.HttpContext.Response.WriteAsync(stringBuilder.ToString());
Run Code Online (Sandbox Code Playgroud)
但这会使整个页面空白。
我正在寻找内置在Asp.Core 2.0中的nopCommerce 4.0的解决方案
httpcontext ×10
asp.net ×4
asp.net-mvc ×4
c# ×3
asp.net-core ×1
caching ×1
datacontext ×1
elmah ×1
json ×1
linq-to-sql ×1
mocking ×1
moq ×1
nopcommerce ×1
routedata ×1
system.web ×1