我看过很多关于何时使用ViewBag/ViewData和ViewModel的帖子,但我无法找到ViewBag生命周期的解释.
例如,我在一个Controller中有两个Action方法:
// POST: /MyModel/Edit/5
[HttpPost]
public ActionResult Edit(MyModel _mymodel){}
Run Code Online (Sandbox Code Playgroud)
和
// GET: /MyModel/Edit/5
public ActionResult Edit(int id){}
Run Code Online (Sandbox Code Playgroud)
如果我在GET操作方法的ViewBag中放置一些值,设置一些表单标签,那么当用户单击"提交"按钮并通过HTTP POST将表单发回服务器时,ViewBag值不再在POST动作方法.
有人可以解释(或提供好文章)ViewBag/ViewData的生命周期吗?
我对ApiController的单元测试使用一些帮助器方法来实例化控制器:
public static ResourcesController SetupResourcesController(HttpRequestMessage request, IResourceMetadataRepository repo, IUnitOfWorkService unitOfWorkService)
{
var config = new HttpConfiguration();
var defaultRoute = config.Routes.MapHttpRoute(RouteNames.DefaultApi , "api/{controller}/{id}");
var routeData = new HttpRouteData(defaultRoute, new HttpRouteValueDictionary { { "controller", "resources" } });
var resourcesController = new ResourcesController(repo, unitOfWorkService)
{
ControllerContext = new HttpControllerContext(config, routeData, request),
Request = request
};
resourcesController.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
resourcesController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
// Compilation fail: The Property 'System.Web.Http.ApiController.User' has no setter.
resourcesController.User = myStubUserPrincipal;
return resourcesController;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何设置控制器的用户属性?
我试过了:
request.Properties.Add("MS_UserPrincipal", myStubUserPrincipal);
Run Code Online (Sandbox Code Playgroud)
但这也不起作用(resourcesController.User属性保持为null).
是否可以让帮助页面样本生成器忽略特定类型的某些属性?
例如,对于POST和PUT请求,我们对对象请求和响应消息使用相同的DTO.当用户POST一个模型(创建一个新记录)时,他们不需要提供ID字段.
但是一旦创建并将新记录序列化到响应主体中,就会包含ID字段并将其返回给客户端.
所以在POST请求示例中,我不希望显示ID字段,因为对于post请求它没有意义.
但是POST响应示例,我确实希望显示ID字段......
我知道有一个ApiExplorerSettings属性可以应用于类或方法......但是属性有什么类似的东西吗?
像这样的东西会很棒:
public class MyDTO
{
[ApiExplorerSettings(IgnoreForRequestApi = true, IgnoreForResponseApi = false)]
public int Id { get; set; }
// Other properties omitted for brevity...
}
Run Code Online (Sandbox Code Playgroud) 我对此做了很多研究.
我正在尝试使用SQL Server 2014恢复数据库,并且它一直保持100%的挂起状态.
很多人建议解决方案是确保使用RECOVERY选项进行恢复.
我试过了,它仍然挂在100%.我已尝试通过SSMS还原对话框,我尝试运行以下SQL语句:
USE [master]
RESTORE DATABASE [MyDB]
FROM DISK = N'C:\MyDB_backup_2015_05_05_010004_1506557.bak'
WITH
FILE = 1,
MOVE N'MyDB_Data' TO N'F:\MSSQL\DATA\MyDB.mdf',
MOVE N'MyDB_Log' TO N'F:\MSSQL\DATA\MyDB_1.ldf',
NOUNLOAD,
REPLACE,
RECOVERY,
STATS = 2
GO
Run Code Online (Sandbox Code Playgroud)
当我通过以下方式检查命令的状态时:
SELECT r.status, r.command, r.wait_type, r.percent_complete
FROM sys.dm_exec_requests r
WHERE r.command like '%restore%' or r.command like '%backup%'
Run Code Online (Sandbox Code Playgroud)
我明白了:
status: suspended
command: RESTORE DATABASE
wait_type: BACKUPTHREAD
percent_complete: 100
Run Code Online (Sandbox Code Playgroud)
从我的阅读中暗示RESTORE正在等待BACKUP完成,但是没有从我的查询返回到sys.dm_exec_requests的BACKUP命令
编辑:再次尝试并运行上述查询以从头开始观察RESTORE的进度后,我可以看到'percent_complete'值正在稳步增加,尽管'status'仍然是'暂停'并且'wait_type'仍为'BACKUPTHREAD'.
因此,尽管它被"暂停",它实际上仍在执行RESTORE.
所以我很茫然......
任何人都有任何想法在这里发生了什么或任何有关如何诊断问题的提示?
干杯!
在我的生产代码中,我们遇到的问题是Request.GetOwinContext()总是返回null.
我设置了一个小型测试WebAPI控制器来尝试隔离问题:
public class TestController : ApiController
{
[HttpGet]
public async Task<IHttpActionResult> GetAsyncContext(string provider)
{
if (HttpContext.Current.GetOwinContext() == null)
return this.BadRequest("No HttpContext.Current Owin Context");
if (Request.GetOwinContext() == null)
return this.BadRequest("No Owin Context");
return this.Ok();
}
[HttpGet]
public IHttpActionResult GetContext(string provider)
{
if (HttpContext.Current.GetOwinContext() == null)
return this.BadRequest("No HttpContext.Current Owin Context");
if (Request.GetOwinContext() == null)
return this.BadRequest("No Owin Context");
return this.Ok();
}
}
Run Code Online (Sandbox Code Playgroud)
起初我以为它可能与异步运行的action方法有关,但是在运行上面的内容之后,事实证明在两个版本中,Request.GetOwinContext()都返回null.
我正在使用Microsoft.AspNet.WebApi.Owin.5.1.1(这似乎是GetOwinContext()扩展方法的定义).
关于这里发生了什么的任何想法?
我正在关注VS2013 SPA模板的示例 - 但是我没有使用Bearer Tokens(这可能是问题但是如果可能的话,我希望能够使用cookie).
以下是我的API控制器中相关操作方法的缩减版本:
[HttpGet]
[AllowAnonymous]
public async Task<IHttpActionResult> ExternalLogin(string provider, string error = null)
{
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
// ...do stuff with externalLogin data
}
Run Code Online (Sandbox Code Playgroud)
以下是请求的基本流程:
用户点击Facebook按钮,将GET发送到/ api/externallogin?provider = Facebook
User.Identity.IsAuthenticated返回false - >返回401结果,中间件将其转换为302,并将"Location"标头设置为facebook登录页面
浏览器进入facebook登录页面(https://www.facebook.com/dialog/oauth?response_type=code&client_id={myClientId}&redirect_uri=http%3A%2F%2Flocalhost%3A54819%2Fsignin-facebook&scope=user_birthday&state={someStateCode})
用户通过Facebook登录 - >导致浏览器调用'redirect_uri',但现在查询字符串中包含'code'和'state'参数,即 http://localhost:54819/signin-facebook?code={someCode}&state={someStateCode}
调用'redirect_uri'的响应是302,其中Location头设置回我的应用程序,还包含两个'Set-Cookie'标题:
http://localhost:54819/api/en-gb/account/externallogin?provider=Facebook然后,浏览器将GET请求发送到步骤5(返回到我的应用程序)的Location头中的URL,并带有以下cookie(根据上面的'Set-Cookie'指令):
问题:User.Identity.IsAuthenticated check在此阶段返回False(实际上User字段基本上是空的)
我想,鉴于AspNet.ExternalCookie肯定是在步骤6的请求中发送的,那么用户就被认证了.
那么,有没有人知道中间件在这个阶段会寻找什么,以便它解码/解密/反序列化cookie并使用户饱和?
这是Startup.Auth我有:
public …Run Code Online (Sandbox Code Playgroud) 的背景:
我在负载均衡器后面的IIS 7.0上托管了一个服务,它在流量通过时解密SSL.
服务所需的安全模式是混合模式,即TransportWithMessageSecurity
为了使服务能够接受HTTP流量,同时允许客户端通过SSL与Load Balancer进行通信,我创建了一个用户定义绑定,它将自定义HttpTransportBindingElement添加到其通道堆栈.
自定义HttpTransportBindingElement依次向框架声明它能够加密和签名消息......因此,当流量通过HTTP进入时,Framework不会抱怨,因为Transport声称它正在签名/加密消息. ..即使不是.
(对于所有相关人员,这已被确定为可接受的安全性,因为消息或者应该通过SSL到达负载均衡器......)
问题:
当我们使用svcutil.exe生成客户端代理时,生成的自动生成的app.config文件包含通过HTTP寻址的服务的端点.这应该通过HTTPS.
此外,<customBinding>节点中的<transport>元素在需要是<httpsTransport>元素时定义为<httpTransport>元素.
我怀疑这是因为使用自定义HttpTransportBindingElement(如上所述),由服务器上的框架生成的WSDL依次使用HTTP地址而不是HTTPS>构建.
自动生成的客户端app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="myBindingEndpoint">
<!-- WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'http://tempuri.org/': -->
<!-- <wsdl:binding name='myBindingEndpoint'> -->
<!-- <sp:HttpToken xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">..</sp:HttpToken> -->
<security defaultAlgorithmSuite="Default" authenticationMode="CertificateOverTransport"
requireDerivedKeys="true" securityHeaderLayout="Strict" includeTimestamp="true"
keyEntropyMode="CombinedEntropy" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
<localClientSettings cacheCookies="true" detectReplays="false"
replayCacheSize="900000" maxClockSkew="00:05:00" maxCookieCachingTime="Infinite"
replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00"
sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true"
timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" />
<localServiceSettings detectReplays="false" issuedCookieLifetime="10:00:00"
maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="00:05:00"
negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00"
sessionKeyRenewalInterval="15:00:00" …Run Code Online (Sandbox Code Playgroud) 我一直在研究保护MVC 5应用程序的最佳方法.
我们有一个带有许多WebAPI控制器的Web.csproj以及一个有两个区域的MVC站点 - 一个用于Admin,然后用于面向公众的网站.
阅读本文后说明基本控制器是最好的方法,我决定采用这种方法.
但是,我个人对使用基本控制器并不行(对于我的一些推理,请参阅此stackoverflow答案).
因此,鉴于我正在使用MVC 5(ASP.Net身份和OWIN身份验证) - 任何人都可以了解每种方法的优缺点吗?
背景
我们正在使用 ASP.Net Core 和 Entity Framework Core 2.2 构建一个 Web 应用程序
我们正在连接到旧数据库。设置是有 16 个数据库,所有数据库都具有完全相同的模式,保存不同的上下文数据。我们无法改变这一点。
我们需要在运行时根据请求参数连接到特定数据库。
想象一下,母公司下的每个业务都有一个数据库。
想象一下,每个数据库都有像 Employee、Client 和 Shift(员工为 Client 工作的轮班)这样的表。
还有一个“中央”数据库,其中包含所有其他数据库中的通用信息,例如设置等。
我们需要在单个列表视图中列出所有企业的所有员工。
我们计划使用中央数据库中的 SQL 视图来检索这些数据,该视图只是在其他每个数据库之间执行 UNION(如果您有关于如何更好地执行此操作的建议,请分享)。
CREATE VIEW dbo.v_all_employees AS
SELECT EmployeeId, Fullname, 1 AS BusinessId FROM BusinessA.dbo.Employees
UNION ALL SELECT EmployeeId, Fullname, 2 AS BusinessId FROM BusinessB.dbo.Employees
-- etc. etc.
Run Code Online (Sandbox Code Playgroud)
我们有一组模型代表所有数据库中的所有实体(表),因为它们共享完全相同的模式,例如一个 Employee 类,一个 Client 类等。
用例
用户通过此路线转到网页以查看所有企业的员工列表:
然后,用户单击单个员工的“详细信息”链接以查看更多详细信息,将用户带到以下网址:
http://example.org/employees/details?employeeId=123&businessId=xyz
我所坚持的是我们如何在运行时实例化特定于业务的 DbContext,给定 BusinessId。
我想出了三种方法(现在第四种感谢@mylee)来达到预期的结果,并且正在寻找来自社区的反馈。
每个选项都假定每个 DbContext 将实现一个接口,该接口公开所有 DbSets 和 DbContext 方法,然后我们将使用工厂模式来确定要使用哪个 DbContext 实现。
第一个选项: 只需让工厂根据请求参数“bizId”创建正确的 DbContext。 …
我正在尝试运行命令:
npx webpack
Run Code Online (Sandbox Code Playgroud)
它告诉我它需要 webpack-cli 并询问是否应该安装它,我说“是”。然后它给了我:
PS C:\_ljdev\webpack demo> npx webpack
npx: installed 321 in 11.89s
One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
- webpack-cli (https://github.com/webpack/webpack-cli)
The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no): yes
Installing 'webpack-cli' (running 'npm install -D webpack-cli')...
npm WARN webpack-cli@3.2.3 requires a peer of webpack@4.x.x but none is installed. You must …Run Code Online (Sandbox Code Playgroud) owin ×3
c# ×2
.net-core ×1
cookies ×1
ef-core-2.2 ×1
facebook ×1
iprincipal ×1
npm ×1
npx ×1
restore ×1
sql-server ×1
ssl ×1
svcutil.exe ×1
viewbag ×1
wcf ×1
webpack ×1
webpack-cli ×1