2

我有一个在 iis 7.5 上运行的 mvc 4 应用程序。该应用程序生成一个产品目录,其中包含分配给每个产品的图像。

有时有些产品没有分配任何图像,在这种情况下,我想包含一个占位符图像而不是什么都没有。直到运行时和 404 发生时,图像才不存在。

我正在考虑在 IIS 中设置一个 url 重写规则,如果从匹配条件的图像返回 404,则显示默认图像。我对此有几个问题:

有可能吗?如果可以,怎么办?这样做是否存在性能问题?有没有其他方法可以实现上述目标?

4

2 回答 2

1

If you really want to handle this with IIS you could use the custom 404 error page configuration.
I don't know about the performance with this solution but I don't see a reason why it would be an issue.

  1. Setup a Virtual Directory containing all your images (let's call it my_images).

  2. Add your generic picture at the virtual directory root (so this picture is available using the url http://yourwebsite.com/my_images/generic.jpg).

  3. In IIS manager select your my_images virtual directory and under Error Pages edit the 404 custom error page as following:

    404

You should now have your generic picture when a 404 error is triggered when trying to access a resource under your virtual directory my_images.

Limitation:

The custom 404 error page is not limited to the image format so any request triggering the 404 error under your virtual directory will render the generic image.
If you want to test using localhost, you need to click on Edit Feature Settings... and change the value to Custom error pages:

features

于 2013-02-18T16:58:27.703 回答
1

好问题。我的第一个想法是找出文件是否存在于服务器上。我假设这不像拥有图像的数据库列那么容易。

也许您有一个场景,您查看一个文件夹,其中图像与 productId(或类似名称)同名。您可以使用 System.IO.FileExists() 来确定文件是否存在。这可能不是非常有效。

另一个想法可能是查看文件所在的目录并将它们放入某种字典中。您可以将其存储在应用程序缓存中。您可以在渲染图像之前查看缓存。当然,您想要一种刷新该字典的方法(即为该产品上传产品图像)

我不知道重写将如何工作。我认为你可以做一些工作来避免这样做。

<img src="(@Dictionary[key] != null ? Model.Image : Model.EmptyImage)" />
于 2013-02-17T21:48:35.873 回答